<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="10" class="add_cate">
        <el-col :span="2">
          <el-button type="primary" @click="showDialog(true,null)">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格内容区域 -->
      <tree-table
        :data="cateListData"
        :columns="columns"
        border
        show-index
        index-text="#"
        :expand-type="false"
        :selection-type="false"
        :show-row-hover="false"
      >
        <template slot="isok" slot-scope="scope">
          {{ scope.row.lenght }}
          <i
            class="el-icon-success"
            v-if="!scope.row.cat_deleted"
            style="color:#00FF00"
          ></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          {{ scope.row.lenght }}
          <el-tag size="mini" v-if="scope.row.cat_level  === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level  === 1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="operation" slot-scope="scope">
          {{ scope.row.lenght }}
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showDialog(false,scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delectCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="categoriesParam.pagenum"
        :page-sizes="[1, 2, 3, 5, 10]"
        :page-size="categoriesParam.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataTotal"
      ></el-pagination>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isDialogVisible"
      width="50%"
      @close="dialogClosed"
    >
      <el-form ref="dialogFormRef" :rules="dialogFormRules" :model="formData" label-width="100px">
        <el-form-item prop="cat_name" label="分类名称：">
          <el-input v-model="formData.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" v-show="isAddCate">
          <el-cascader
            v-model="selectValue"
            :options="selectList"
            @change="selectChange"
            :props="selectOptions"
            change-on-select
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- :props="selectOptions" -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogTitle: "添加分类",
      isAddCate: true,
      categoriesParam: {
        type: 3,
        pagenum: 1,
        pagesize: 2
      },
      cateListData: [],
      dataTotal: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
          // width: '400px',
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "operation"
        }
      ],
      isDialogVisible: false,
      formData: {
        id:0,
        cat_pid: 0,
        cat_name: "",
        cat_level: 0
      },
      selectValue: [],
      selectList: [],
      selectOptions: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      dialogFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在2到8个字符", trigger: "blur" }
        ]
      }
    };
  },

  created() {
    this.getCateDataList();
  },
  methods: {
    //分页的每页条数 改变回调
    handleSizeChange(pageSize) {
      this.categoriesParam.pagesize = pageSize;
      this.getCateDataList();
    },
    //当前页数改变 回调
    handleCurrentChange(pageNum) {
      this.categoriesParam.pagenum = pageNum;
      this.getCateDataList();
    },

    //  商品分类的请求
    getCateDataList() {
      this.$httpReq
        .get("categories", { params: this.categoriesParam })
        .then(res => {
          console.log("==商品分类==>" + JSON.stringify(res));
          if (res.meta.status === 200) {
            this.cateListData = res.data.result;
            this.dataTotal = res.data.total;
          } else {
            var msg = res.meta.status;
            this.$message.error(msg);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //  指定一二级商品分类的请求
    getParentClassList() {
      this.$httpReq
        .get("categories", { params: { type: 2 } })
        .then(res => {
          console.log("==指定一二级商品分类的请求==>" + JSON.stringify(res));
          if (res.meta.status === 200) {
            this.selectList = res.data;
          } else {
            var msg = res.meta.status;
            this.$message.error(msg);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    //显示弹窗
    showDialog(isBool,itemData) {
      this.isAddCate = isBool;
      if (this.isAddCate) {
        (this.dialogTitle = "添加分类"), this.getParentClassList();
        this.isDialogVisible = true;
      } else {
        this.formData.id = itemData.cat_id;
        this.formData.cat_name = itemData.cat_name;
        this.dialogTitle = "编辑分类"; 
        this.isDialogVisible = true;
      }
    },
    //弹窗关闭监听
    dialogClosed() {
      this.$refs.dialogFormRef.resetFields();
      this.selectValue = [];
      this.formData.cat_pid = 0;
      this.formData.cat_level = 0;
    }, 
    //选择器 选择监听
    selectChange() {
      const len = this.selectValue.length;
      if (len > 0) {
        this.formData.cat_pid = this.selectValue[len - 1];
        this.formData.cat_level = len;
      } else {
        this.formData.cat_pid = 0;
        this.formData.cat_level = 0;
      }
    }, 

    //dialog 确定
    dialogOK() {
      this.$refs.dialogFormRef.validate(valid => {
        if (!valid) return;
        if (this.isAddCate) {
          //添加分类
         this.$httpReq
            .post("categories", this.formData)
            .then(res => {
              if (res.meta.status === 201) {
                this.$message.success("创建成功");
                this.getCateDataList();
                this.isDialogVisible = false;
              } else {
                var msg = res.meta.status;
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        }else{
          //编辑分类
          this.$httpReq
            .put(`categories/${this.formData.id}`, this.formData)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message.success("编辑成功");
                this.getCateDataList();
                this.isDialogVisible = false;
              } else {
                var msg = res.meta.status;
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        }



      });
    },
    //删除分类
    delectCate(catId)
    {
       this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(()=>{
          console.log("====删除分类===>" + catId);
           this.$httpReq
            .delete(`categories/${catId}`)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message.success("删除分类成功");
                this.getCateDataList();
                this.isDialogVisible = false;
              } else {
                var msg = res.meta.status;
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        }).catch(() => {
              this.$message("取消删除分类");
            });
    }
  }
};
</script>

<style>
.add_cate {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>